
#import <EOAccess/EOAccess.h>

void fetch(void);
void usage(void);

int main (int argc, const char *argv[])
{
   NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

   NS_DURING

     fetch();

   NS_HANDLER

     NSLog(@"%@", [localException reason]);

   NS_ENDHANDLER

   [pool release];
   exit(0);       // insure the process exit status is 0
   return 0;      // ...and make main fit the ANSI spec.
}

void fetch(void)
{
  NSString *modelPath = [[NSUserDefaults standardUserDefaults] stringForKey:@"model"];
  NSString *entityName = [[NSUserDefaults standardUserDefaults] stringForKey:@"entity"];

  EOModel *model;
  EOEditingContext *context;
  EODatabaseDataSource *dataSource;
  NSArray *results;

  if(!modelPath || ![modelPath length] || !entityName || ![entityName length]) {
    usage();
    return;
  }
    
  model = [[EOModel alloc] initWithContentsOfFile:modelPath];

  if(!model) {
    NSLog(@"Unable to load model %@", modelPath);
    return;
  }

  if(![model entityNamed:entityName]) {
    NSLog(@"Entity %@ not found in model %@", entityName, modelPath);
    return;
  }
    
  [[EOModelGroup defaultGroup] addModel:model];

  context = [[EOEditingContext alloc] initWithParentObjectStore:[EOObjectStoreCoordinator defaultCoordinator]];

  dataSource = [[EODatabaseDataSource alloc] initWithEditingContext:context entityName:entityName];
  
  results = [dataSource fetchObjects];
  
  NSLog(@"Result: %@", results);
}

void usage(void)
{
    NSLog(@"Usage: fetch -model <full path for an eomodeld file> -entity <entity name>");
}
